package com.eastcode.mobile.client.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import com.eastcode.base.action.BaseAction;
import com.eastcode.mobile.server.system.entity.User;
import com.eastcode.mobile.server.system.service.UserService;
import com.eastcode.mobile.server.system.view.UserView;
import com.eastcode.mobile.server.util.ServerConstant;
import com.eastcode.mobile.server.util.ServerLocator;

public class LoginAction extends BaseAction {

	private static final long serialVersionUID = 2641505428202850821L;

	private UserService userService = ServerLocator.getUserService();

	Logger log = Logger.getLogger(this.getClass().getName());

	@Override
	protected void execute() {
		prepare(this);
	}

	/**
	 * 登录
	 * 
	 */
	public void login() {

		User user = (User) session.getAttribute(ServerConstant.SYS_USER);
		if (user == null || user.getUserId() == null) {
			String userId = request.getParameter("userId");
			String password = request.getParameter("password");

			UserView view = new UserView();
			Map<String, String> paramMap = new HashMap<String, String>();
			paramMap.put("userId", userId);
			paramMap.put("password", password);
			view.setParamMap(paramMap);

			List<User> userList = userService.searchList(User.class, view);

			if (userList == null || userList.size() == 0) {
				view.setResult("用户名或密码错误！请重新输入！");
				setResult(view);
			} else {
				user = userList.get(0);
				view.setResult("1");
				setResult(view);
			}
		}

		// 登录是否正确
		if (user != null && user.getUserId() != null) {
			session.setAttribute(ServerConstant.SYS_USER, user);
		}

		String from = request.getParameter("from");
		if ("pc".equals(from)) {
			if (user != null) {
				// 跳转到管理页面
				forward("/template/main.ftl");
			} else {
				forward("/template/login.ftl");
			}
		} else {
			// 跳转到结果页面
			forward("/template/ajax/result.ftl");
		}
	}

	/**
	 * 系统用户退出
	 * 
	 * @return
	 */
	public void logout() {
		request.getSession().removeAttribute(ServerConstant.SYS_USER);
		forward("/template/login.ftl");
	}
}
